package org.dreamfly.core.action;

import imageretrievalcopy.ImageContentSearch;
import org.apache.struts2.ServletActionContext;
import org.dreamfly.core.bean.*;
import org.dreamfly.core.service.*;
import org.dreamfly.core.util.CharacterJudger;
import org.dreamfly.core.util.ContentDll;
import org.dreamfly.core.util.ContentDll.VideoInfo;
import org.dreamfly.core.util.RemoteUpload;
import org.dreamfly.core.util.creatMinPicture;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class FileUploadAction extends FileActionSupport {
    
    private Long typeId;  //类型ID
    private String tableId;
    private List<Long> szTypeIds; //用于搜索的ID列表
    private String idList;
    private PictureTypeService pictureTypeService;
    private PictureService pictureService;
    private RadioService radioService;
    private VideoService videoService;
    private ActivityService activityService;
    private ModelService modelService;
    private VideoTypeService videoTypeService;
    private ModelTypeService modelTypeService;
    private String ip;
    private String name;
    private String username;
    private String password;
    private String tableName;
    private String serverName;


    public void setRadioService(RadioService radioService) {
        this.radioService = radioService;
    }

    public void setVideoService(VideoService videoService) {
        this.videoService = videoService;
    }

    public void setActivityService(ActivityService activityService) {
        this.activityService = activityService;
    }

    public void setModelService(ModelService modelService) {
        this.modelService = modelService;
    }

    public String uploadModelPicture() {
        this.upload(UploadFile.UploadFolder.model, "", false);
        if (0 < this.filesFileName.size()) {
            this.filePath = this.filesFileName.get(0);
        }
        return SUCCESS;
    }

    public String uploadActionPicture() {
        this.upload(UploadFile.UploadFolder.activity, "", false);
        if (0 < this.filesFileName.size()) {
            this.filePath = this.filesFileName.get(0);
        }
        return SUCCESS;
    }

    /**
     * 上传用于内容搜索的图片
     *
     * @return success 如果上传成功
     */
    public String uploadTemPicture() {
        this.upload(UploadFile.UploadFolder.temp, "", true);
        if (0 < this.filesFileName.size()) {
            this.filePath = this.filesFileName.get(0);
        }
        return SUCCESS;
    }

    public String uploadTemPictureByType() {
        this.upload(UploadFile.UploadFolder.temp, "", true);
        if (0 < this.filesFileName.size()) {
            this.filePath = this.filesFileName.get(0);
        }
        String configPath = ServletActionContext.getServletContext().getRealPath("/WEB-INF/FTPServer.xml");
        String file = ServletActionContext.getServletContext().getRealPath("/upload/" + filePath);
        RemoteUpload.upFileByConfigXml(configPath,file);
        StringBuilder result = new StringBuilder();
        if (szTypeIds != null) {
            for (Long id : szTypeIds) {
                result.append(id + ",");
            }
        }
        idList = result.toString();
        return SUCCESS;
    }

    /**
     * 上传图片
     *
     * @return success
     */
    public String uploadPicture() throws UnsupportedEncodingException {
        SzPicture szPicture = new SzPicture();
        String classUrl =  this.pictureTypeService.getUnique(typeId).getClassUrl();
        String className = getOriginalName(classUrl) + "/image/";  //生成存放图片的路径
        this.upload(UploadFile.UploadFolder.picture, className, false);
        if (0 < this.filesFileName.size()) {
            this.filePath = this.filesFileName.get(0);
            szPicture.setPictureUrl(filePath);
            szPicture.setSzPictureType(this.pictureTypeService.getUnique(typeId));
        }
        try {
            creatMinPicture cmp = new creatMinPicture(filePath);
            cmp.resizeFix(160, 160);
            szPicture.setMinPictureUrl(cmp.getRelativeDestFile());
            szPicture.setDisrate(cmp.getSrcWidth() + "*" + cmp.getSrcHeight());
            szPicture.setSize(cmp.getSize()/1024);
            szPicture.setFileType(cmp.getFileType());
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        pictureService.saveOrUpdate(szPicture);
        ImageContentSearch ics = new ImageContentSearch();
        String args0 = ServletActionContext.getServletContext().getRealPath(UploadFile.uploadFolder) + "\\" + this.filesFileName.get(0).replace("/", "\\");
        String args1 = this.filesFileName.get(0);
        args1 = args1.substring(args1.lastIndexOf("/"));
        args1 = args1.substring(1, args1.length());
        String args2 = args0.substring(0, args0.indexOf("image")) + "index";
        ics.addImage(args0, args1, args2);
        if (null != szPicture.getId()) {
            sendId(szPicture.getId());
            return null;
        } else
            return INPUT;

    }

    private String getOriginalName(String classUrl) {
        if(null != classUrl){
        int start = classUrl.lastIndexOf("\\") +1;
            int end = classUrl.length() ;
            return classUrl.substring(start,end);
        }else {
            return "";
        }
    }

    /**
     * 视频文件上传
     *
     * @return
     */
    public String uploadVideo() {

        this.upload(UploadFile.UploadFolder.video, "", false);


        //添加到数据库
        SzVideo video = new SzVideo();
        SzVideoType vt = new SzVideoType();
        vt.setTypeId(1L);
        video.setSzVideoType(vt);
        video.setFileType("avs");
        video.setMinPictureUrl("??");
        video.setVideoUrl("??");
        video.setVideoUrl(this.filesFileName.get(0));
        try {
            video.setSize(getFileSize(this.filesFileName.get(0)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuffer videoDir = new StringBuffer(ServletActionContext
                .getServletContext().getRealPath(
                UploadFile.uploadFolder + "\\"
                        + this.filesFileName.get(0)));
        String videoMinDir = videoDir.substring(0, videoDir.lastIndexOf("\\")) + "\\minPic";
        if (!new File(videoMinDir).exists()) {
            new File(videoMinDir).mkdir();
        }
        video.setDisrate("");
        String pictureUrl = videoMinDir + "\\" + this.filesFileName.get(0).substring(this.filesFileName.get(0).lastIndexOf("/") + 1, this.filesFileName.get(0).length());
        pictureUrl = pictureUrl.substring(0, pictureUrl.lastIndexOf(".")) + "0.bmp";
        pictureUrl = pictureUrl.substring(pictureUrl.indexOf("video"), pictureUrl.length());
        pictureUrl = pictureUrl.replace("\\", "/");
        System.out.println(pictureUrl);
        video.setMinPictureUrl(pictureUrl);
        videoService.saveOrUpdate(video);


        //添加到videoInfo
        VideoInfo.ByReference videoInfo = new VideoInfo.ByReference();
        videoInfo.pcFileType = "avs";
        videoInfo.pcFilmType = "高清";

        videoInfo.pcFilePath = videoDir.toString();
        videoInfo.pcSeverName = serverName;

        System.out.println(videoMinDir);

        videoInfo.pcKeyFrameFolder = videoMinDir;
        System.out.println(video.getId());
        videoInfo.iFileID = Integer.parseInt(String.valueOf(video.getId()));
        System.out.println("pcFileType:" + videoInfo.pcFileType);
        System.out.println("pcFilmType:" + videoInfo.pcFilmType);
        System.out.println("pcFilePath:" + videoInfo.pcFilePath);
        System.out.println("pcSeverName:" + videoInfo.pcSeverName);
        System.out.println("pcKeyFrameFolder:" + videoInfo.pcKeyFrameFolder);
        System.out.println("iFileID:" + videoInfo.iFileID);
        System.out.println(ContentDll.INSTANCE.OpenDatabase(ip, name, username, password, tableName));
        System.out.println(ContentDll.INSTANCE.Input_data(videoInfo, CharacterJudger.isUTF_8()));
        Long typeId = changeType(videoInfo.iFilmWidth, videoInfo.iFilmHight);
        String disrate = videoInfo.iFilmWidth + "*" + videoInfo.iFilmHight;
        videoService.changeType(video.getId(), typeId, disrate);
        sendId(video.getId());
        return null;
    }

    /**
     * 动作库文件上传
     *
     * @return
     */
    public String uploadActivity() throws IOException {
        this.upload(UploadFile.UploadFolder.activity, "", false);
        SzActivity activity = new SzActivity();
        activity.setFileType("bvh");
        activity.setMinPictureUrl("null");
        activity.setActivityUrl(this.filesFileName.get(0));
        activity.setSize(getFileSize(this.filesFileName.get(0)));
        activityService.saveOrUpdate(activity);
        sendId(activity.getId());
        return null;
    }

    /**
     * 模型文件上传
     *
     * @return
     * @throws IOException
     */
    public String uploadModel() throws IOException {
        this.upload(UploadFile.UploadFolder.model, "", false);
        SzModel model = new SzModel();
        model.setSzModelType(modelTypeService.getUnique(typeId));
        model.setMinPictureUrl("null");
        model.setModelUrl(this.filesFileName.get(0));
        model.setSize(getFileSize(this.filesFileName.get(0)));
        model.setFileType("3ds");
        modelService.saveOrUpdate(model);
        sendId(model.getId());
        return null;
    }

    /**
     * 音频文件上传
     *
     * @return
     */
    public String uploadRadio() throws IOException {
        this.upload(UploadFile.UploadFolder.radio, "", false);
        SzRadio radio = new SzRadio();
        radio.setRadioUrl(this.filesFileName.get(0));
        radio.setSize(getFileSize(this.filesFileName.get(0)));
        radio.setFileType("mp3");
        radioService.saveOrUpdate(radio);
        sendId(radio.getId());
        return null;
    }

    /**
     * 将数据库中ID传到前台
     *
     * @param Id 文件ID
     */
    private void sendId(Long Id) {
        HttpServletResponse res = ServletActionContext.getResponse();
        try {
            if (null != Id)
                res.getWriter().print(Id);
            else
                res.getWriter().print(-1);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    private Long changeType(int width, int length) {
        Integer disrate = width * length;
        if (disrate < 150000) {
            return videoTypeService.searchByName("低").getTypeId();
        } else if (disrate > 720000) {
            Long id = videoTypeService.searchByName("高").getTypeId();
            return id;
        } else {
            return videoTypeService.searchByName("中").getTypeId();
        }
    }

    /**
     * 获取文件大小
     *
     * @param path 文件路径
     * @return 文件大小
     * @throws IOException
     */
    private Integer getFileSize(String path) throws IOException {
        String filepath = ServletActionContext.getServletContext().getRealPath(UploadFile.uploadFolder + "/" + path);
        File tempF = new File(filepath);
        if (tempF.exists()) {
            FileInputStream fis = new FileInputStream(tempF);
            return fis.available() /1024;
        }
        return -1;
    }

    /**
     * 获取文件后缀名
     *
     * @param filePath
     * @return
     */
    public String getFileType(String filePath) {
        String fileType = filePath.substring(filePath.lastIndexOf("."), filePath.length());
        return fileType;
    }

    public void setVideoTypeService(VideoTypeService videoTypeService) {
        this.videoTypeService = videoTypeService;
    }

    public String getTableId() {
        return tableId;
    }

    public void setTableId(String tableId) {
        this.tableId = tableId;
    }

    public void setPictureService(PictureService pictureService) {
        this.pictureService = pictureService;
    }

    public Long getTypeId() {
        return typeId;
    }

    public void setTypeId(Long typeId) {
        this.typeId = typeId;
    }

    public void setPictureTypeService(PictureTypeService pictureTypeService) {
        this.pictureTypeService = pictureTypeService;
    }

    public List<Long> getSzTypeIds() {
        return szTypeIds;
    }

    public void setSzTypeIds(List<Long> szTypeIds) {
        this.szTypeIds = szTypeIds;
    }

    public String getIdList() {
        return idList;
    }

    public void setIdList(String idList) {
        this.idList = idList;
    }

    public void setModelTypeService(ModelTypeService modelTypeService) {
        this.modelTypeService = modelTypeService;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public void setServerName(String serverName) {
        this.serverName = serverName;
    }
}
